import 'package:ac/common/ac_pv_manager.dart';
import 'package:ac/common/style.dart';
import 'package:ac/data/ac_app_preferences.dart';
import 'package:ac/data/ac_device_tool.dart';
import 'package:ac/data/ac_global_controller.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/model/ac_login_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';

import '../../api/ac_urls.dart';
import '../../route/ac_route_pages.dart';
import 'ac_login_state.dart';

class AcLoginLogic extends GetxController {
  final AcLoginState state = AcLoginState();

  void changeAgreeStatus() {
    state.checkAgreement.value = !state.checkAgreement.value;
  }

  Future<void> appleLogin() async {
    if (!state.checkAgreement.value) {
      var result = await _showConfirmDialog();
      if (result) {
        state.checkAgreement.value = true;
      } else {
        return;
      }
    }
    LogPvManger.stat(page: LogPages.appleLoginPage);
    //核心就这一个方法，去获取登录用户信息
    AuthorizationCredentialAppleID credential =
        await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );

    var result = await AcUrls.login
        .post(showLoading: true, showErrorMessage: false, queryParameters: {
      "oauthType": 3,
      "token": credential.identityToken,
    });
    if (result?["code"] == 0) {
      _handelLoginSuccess(result['data']);
    }
  }

  Future<void> fastLogin() async {
    if (!state.checkAgreement.value) {
      var result = await _showConfirmDialog();
      if (result) {
        state.checkAgreement.value = true;
      } else {
        return;
      }
    }
    LogPvManger.stat(page: LogPages.quickLoginPage);
    var result = await AcUrls.login
        .post(showLoading: true, showErrorMessage: false, queryParameters: {
      "oauthType": 4,
      "token": AcDeviceTool().foDeviceId,
    });
    if (result?["code"] == 0) {
      _handelLoginSuccess(result['data']);
    }
  }

  Future<bool> _showConfirmDialog() async {
    final TapGestureRecognizer termsProtocolRecognizer = TapGestureRecognizer();
    final TapGestureRecognizer privacyProtocolRecognizer = TapGestureRecognizer();
    var result = await Get.dialog(Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 315.w,
          height: 278.h,
          padding: EdgeInsets.all(24.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.r),
          ),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image.asset("images/logo.png",width: 52.w,height: 52.w,),
              SizedBox(height: 16.h),
              Image.asset("images/app_name.png",width: 100.w,),
              const Spacer(),
              Text.rich(TextSpan(
                children: [
                  TextSpan(
                    text: "By using our App you agree with our \n",
                    style: TextStyle(fontSize: 14.sp, color: textColorBlack),
                  ),
                  TextSpan(
                    text: "Terms of Use",
                    style: TextStyle(
                      decoration: TextDecoration.underline,
                      fontSize: 14.sp,
                      color: textColorBlack,
                    ),
                    recognizer: termsProtocolRecognizer
                      ..onTap = () {
                        //打开用户协议
                        openUserProtocol();
                      },
                  ),
                  TextSpan(
                    text: " and ",
                    style: TextStyle(fontSize: 14.sp, color: textColorBlack),
                  ),
                  TextSpan(
                    text: "Privacy Policy",
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: textColorBlack,
                      decoration: TextDecoration.underline,
                    ),
                    recognizer: privacyProtocolRecognizer
                      ..onTap = () {
                        //打开用户协议
                        openPrivacyProtocol();
                      },
                  ),
                ],
              )),
              SizedBox(height: 24.h),
              GestureDetector(
                onTap: () {
                  Get.back(result: true);
                },
                child: Container(
                  width: 198.h,
                  height: 40.h,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    gradient: const LinearGradient(
                      colors: [
                        Color(0xFFFFC371),
                        Color(0xFFFF5F6D),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(58.r),
                  ),
                  child: Text(
                    "Agree and Continue",
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),
              SizedBox(height: 16.h,),
              GestureDetector(
                onTap: () {
                  Get.back(result: false);
                },
                child: Text(
                  "Cancel",
                  style: TextStyle(
                    color: textColorBlack.withOpacity(0.3),
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        )
      ],
    ));
    return result ?? false;
  }
  void _handelLoginSuccess(Map<String, dynamic> result) async {
    LogPvManger.stat(page: LogPages.loginSuccessPage);
    AcLoginModel model = AcLoginModel.fromJson(result);
    AcUserManager.setUserInfoModel(model);
    EasyLoading.show(status: 'loading...', maskType: EasyLoadingMaskType.black);
    await AcUserManager.initBloggerListCompleter.future.catchError((e){
      EasyLoading.dismiss();
    });
    await AcUserManager.initVideoListCompleter.future.catchError((e){
      EasyLoading.dismiss();
    });
    EasyLoading.dismiss();
    //跳转首页
    Get.offAllNamed(AcRouteNames.home);
  }


  void openUserProtocol() {
    LogPvManger.stat(page: LogPages.termsPage);
    Get.toNamed(AcRouteNames.webview,
        parameters: {"url": AcUrls.userAgreement, "title": "Terms of Use"});
  }

  void openPrivacyProtocol() {
    LogPvManger.stat(page: LogPages.privacyPage);
    Get.toNamed(AcRouteNames.webview,
        parameters: {"url": AcUrls.privacy, "title": "Privacy Policy"});
  }
}
